﻿using System;
using System.Data;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Assets;
using System.Text;
using System.IO;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Models;
using System.Collections.Generic;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using System.Threading;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;

namespace ChinaDynastyTours.Views
{
    public partial class BatchHotelOrdersForm : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _dtBatchHotelOrder;
        private bool m_checkStatus = false;

        public BatchHotelOrdersForm()
        {
            InitializeComponent();

            //默认为本月1日起，一年后1日止
            dateStart.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year, DateTime.Now.Month));
            dateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + 1, DateTime.Now.Month));


            //初始化团下拉列表
            DataSet ds = TeamGroupCtrl.GetAllIDForTeamGroup();
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    btnTeamGroupID.Properties.Items.Add(dr["TourGroupID"].ToString().Trim());
            }
        }

        private void btnProviders_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ProviderSelectedToolForm hotelServiceForm = new ProviderSelectedToolForm() { _ProviderTypes = new ProviderTypeEnum[] { ProviderTypeEnum.宾馆 } };

            if (hotelServiceForm.ShowDialog(this) == DialogResult.OK)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.Tag= hotelServiceForm.ReturnProviderID;
                btnEdit.EditValue = hotelServiceForm.ReturnProviderName;
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string providerId = btnProviders.Tag == null ? "" : btnProviders.Tag.ToString();

            _dtBatchHotelOrder = HotelOrderCtrl.GetBatchHotelOrderData(btnTeamGroupID.Text, providerId, dateStart.DateTime, dateEnd.DateTime);
            hotelProviderGridControl.DataSource = AddGridSelectedColumn(_dtBatchHotelOrder);
        }

        private void btnPreviewAndPrint_Click(object sender, EventArgs e)
        {
            //hotelProviderGridView.ClearSelection();
           int[] rowIds = MutilRow(hotelProviderGridView);

            if (rowIds.Length == 0) return;
            
            StringBuilder hotelNames = new StringBuilder();
            BatchHotelOrderDataSet hotelOrderDs = new BatchHotelOrderDataSet();

            hotelNames.AppendFormat(_dtBatchHotelOrder.Rows[rowIds[0]]["ProviderName"].ToString());

            for (int i = 0; i < rowIds.Length; i++)
            {
                if (_dtBatchHotelOrder.Rows[rowIds[i]]["ProviderName"].ToString() !=  hotelNames.ToString())
                {
                    MessageBox.Show("请选择同一供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            
            
            //获取宾馆信息，填充到打印数据集中

            for (int i = 0; i < rowIds.Length; i++)
            {
                hotelOrderDs.Tables["BatchHotelOrder"].ImportRow(hotelProviderGridView.GetDataRow(rowIds[i]));
            }

            BatchHotelOrderReport hotelReport = new BatchHotelOrderReport(hotelNames.ToString());
            hotelReport.DataSource = hotelOrderDs;
            if (sender.Equals(btnPreview))
                hotelReport.ShowPreviewDialog();
            if (sender.Equals(btnPrint))
            {
                if (hotelReport.PrintDialog() == DialogResult.OK)//打印完毕之后将订单状态变为‘已定’
                {
                    ModifyOrderState(rowIds);
                    MessageBox.Show("打印完毕！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (sender.Equals(btnEMail))
            {
                #region 发送EMail
                ProviderEntity entity;
                StringBuilder info = new StringBuilder();
                List<string> receiveMail = new List<string>();
                List<string> files = new List<string>();
                StringBuilder recipients = new StringBuilder();

                info.Append("请核对当前选择内容的供应商信息【注意E-Mail地址是否正确】：\r\n");
                for (int i = 0; i < rowIds.Length; i++)
                {
                    entity = BaseInfoCtrl.GetProviderDataByID(_dtBatchHotelOrder.Rows[rowIds[i]]["ProviderID"].ToString());
                    if (entity == null)
                    {
                        info.Append("\r\n供应商：无");
                        info.Append("\r\nE-Mail：无\r\n");
                    }
                    else
                    {
                        info.AppendFormat("\r\n供应商：{0}", entity.ProviderName);
                        info.AppendFormat("\r\nE-Mail：{0}\r\n", entity.email == "" ? "无" : entity.email);
                        recipients.Append(entity.ProviderName + "|");
                        receiveMail.Add(entity.email);
                    }
                }
                info.AppendFormat("\r\n确认发送吗？");

                if (MessageBox.Show(info.ToString(), "EMail发送", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "hotel.pdf");
                    hotelReport.ExportToPdf(file);
                    if (File.Exists(file))
                    {
                        try
                        {
                            files.Add(file);
                            string departmentId = UserInfoCtrl.GetUserInfoForDepartmentID(Thread.CurrentPrincipal.Identity.Name);
                            if (!string.IsNullOrEmpty(departmentId))
                            {
                                DataTable dtUserInfo = UserInfoCtrl.GetUserInfoData(Thread.CurrentPrincipal.Identity.Name);
                                EMailHelper.SendMail(receiveMail, "订房单", "内容见附件", files, dtUserInfo.Rows[0]["EMail"].ToString(), recipients.ToString(), "", "", LogTypeEnum.操作类);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("发送EMail过程出现错误：" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        finally
                        {
                            File.Delete(file);
                        }
                        ModifyOrderState(rowIds);//发送完毕之后将订单状态变为‘已定’
                        MessageBox.Show("发送成功！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("发送失败,生成报表文件失败！", "信息提示");
                    }
                } 
                #endregion
            }
        }

        private void ModifyOrderState(int[] rowIds)
        {
            string HotelOrderID = "";
            foreach (int id in rowIds)
            {
                HotelOrderID = hotelProviderGridView.GetRowCellValue(id, "HotelOrderID").ToString();
                HotelOrderCtrl.UpdateHotelOrderStateData(HotelOrderID, OrderStateEnum.已订);
                hotelProviderGridView.SetRowCellValue(id, "OrderState", OrderStateEnum.已订);
            }
        }



        #region 多选函数
        /// <summary>
        /// 添加‘选择’附加列
        /// </summary>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        private DataTable AddGridSelectedColumn( DataTable dtSource)
        {
            dtSource.Columns.Add("Selected", typeof(bool));
            return dtSource;
        }
        /// <summary>
        /// 确定是否为全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hotelProviderGridView_Click(object sender, EventArgs e)
        {
            if (DevGridCheckControl.ClickGridCheckBox(this.hotelProviderGridView, "Selected", m_checkStatus))
            {
                m_checkStatus = !m_checkStatus;
            }
        }
        /// <summary>
        /// 画列头复选框（全选框）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hotelProviderGridView_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "Selected")
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DevGridCheckControl.DrawCheckBox(e, m_checkStatus);
                e.Handled = true;
            }
        }
        //private void hotelProviderGridView_DataSourceChanged(object sender, EventArgs e)
        //{
            //GridColumn column = this.hotelProviderGridView.Columns.ColumnByFieldName("Selected");
            //if (column != null)
            //{
            //    column.Width = 80;
            //    column.OptionsColumn.ShowCaption = false;
            //    column.ColumnEdit = new RepositoryItemCheckEdit();
            //}
        //}

        private int[] MutilRow(GridView gv)
        {
            List<int> rowIds = new List<int>();
            for (int i = 0; i < gv.RowCount; i++)
            {
                object objValue = gv.GetRowCellValue(i, "Selected");
                if (objValue != null)
                {
                    bool check = false;
                    bool.TryParse(objValue.ToString(), out check);
                    if (check)
                    {
                        rowIds.Add(i);
                    }
                }
            }
            return rowIds.ToArray();
            //object selected;
            //for (int i = 0; i < gv.RowCount; i++)
            //{
            //    selected = gv.GetRowCellValue(i, "Selected");

            //    if (string.IsNullOrEmpty(selected.ToString())) continue;

            //    if (Convert.ToBoolean(selected) == true)
            //    {
            //        gv.SelectRow(i);
            //    }
            //}
            //return gv.GetSelectedRows();
        } 
        #endregion

    }
}
